package com.library.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.library.context.BaseContext;
import com.library.dto.FavoriteDTO;
import com.library.dto.PageQueryDTO;
import com.library.entity.Book;
import com.library.mapper.BookMapper;
import com.library.mapper.UserFavoriteMapper;
import com.library.result.PageResult;
import com.library.service.FavoriteService;
import com.library.vo.FavoriteVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class FavoriteServiceImpl implements FavoriteService {

    @Autowired
    private UserFavoriteMapper userFavoriteMapper;
    @Autowired
    private BookMapper bookMapper;

    @Override
    public void save(FavoriteDTO favoriteDTO) {
        //获得当前用户id
        Long userId = BaseContext.getCurrentId();
        favoriteDTO.setUserId(userId);
        //获得书名
        Book book = bookMapper.getBookByBookId(favoriteDTO.getBookId());
        favoriteDTO.setBookTitle(book.getTitle());
        //如果用户已经收藏过，则更新书签页
        if (userFavoriteMapper.getByUserIdAndBookId(favoriteDTO.getUserId(), favoriteDTO.getBookId()) != null) {
            userFavoriteMapper.update(favoriteDTO);
        }
        else{
            //如果用户没有收藏过，则插入
            userFavoriteMapper.save(favoriteDTO);
        }


    }

    @Override
    public PageResult getByUserId(Long userId, PageQueryDTO pageQueryDTO) {
        if(pageQueryDTO == null){
            pageQueryDTO = new PageQueryDTO();
            pageQueryDTO.setPage(1);
            pageQueryDTO.setPageSize(10);
        }
        PageHelper.startPage(pageQueryDTO.getPage(),pageQueryDTO.getPageSize());
        Page<FavoriteVO> page = userFavoriteMapper.getByUserId(userId);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public void delete(Long bookId, Long userId) {
        userFavoriteMapper.delete(bookId, userId);
    }
}
